package com.lxs.mall.service.Impl;

import com.lxs.mall.exception.LxsMallException;
import com.lxs.mall.exception.LxsMallExceptionEnum;
import com.lxs.mall.model.dao.UserMapper;
import com.lxs.mall.model.pojo.User;
import com.lxs.mall.service.UserService;
import com.lxs.mall.util.Md5Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;

/**
 * UserServiceImpl实现类
 *
 * @author 小松
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;

    @Override
    public User getUser() {
        return userMapper.selectByPrimaryKey(1);
    }

    @Override
    public void register(String username, String password,String emailAddress) throws LxsMallException {
        //查询用户名是否存在,不允许重名
        User result = userMapper.selectByName(username);
        if (result != null) {
            throw new LxsMallException(LxsMallExceptionEnum.NAME_EXISTED);
        }
        //通过写到数据库
        User user = new User();
        user.setUsername(username);
        user.setEmailAddress(emailAddress);
        try {
            user.setPassword(Md5Utils.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        int count = userMapper.insertSelective(user);
        if (count == 0) {
            throw new LxsMallException(LxsMallExceptionEnum.INSERT_FAIL);
        }
    }

    @Override
    public User login(String username, String password) throws LxsMallException {
        String md5Password = null;
        try {
            md5Password = Md5Utils.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        User user = userMapper.selectLogin(username, md5Password);
        if (user == null) {
            throw new LxsMallException(LxsMallExceptionEnum.WRONG_PASSWORD);
        }
        return user;
    }

    @Override
    public void updateInformation(User user) throws LxsMallException {
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount == 0) {
            throw new LxsMallException(LxsMallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public boolean checkAdmin(User user) {
        return user.getRole().equals(2);
    }

    @Override
    public boolean checkEmailAddress(String emailAddress) {
        User user = userMapper.selectOneByEmailAddress(emailAddress);
        if (user != null) {
            return false;
        }
        return true;
    }
}
